package top.appx.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.appx.dao.BaseDao;

import javax.annotation.Resource;

/**
 * Created by zwy on 2015-5-20.
 */
public class BaseDaoImpl<T> implements BaseDao<T> {

    @Resource
    protected SessionFactory sessionFactory;

    protected Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }

    public  T getById(Class<T> entityClass,int id){
        return (T)getCurrentSession().get(entityClass,id);
    }

    @Transactional
    public  void save(T entity){
        getCurrentSession().save(entity);
    }
    @Transactional(propagation= Propagation.REQUIRED , rollbackFor = java.lang.Exception.class)
    public void update(T entity) {
        getCurrentSession().update(entity);
    }

    @Transactional
    public  void saveOrUpdate(T entity){
        getCurrentSession().saveOrUpdate(entity);
    }

    @Transactional
    public void delete(T entity) {
        getCurrentSession().delete(entity);
    }
}
